package gui;

import gui.event.SelectionEvent;
import gui.event.SelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;

//Class for game menu component, witch has a fixed size stretched to the edges of the frame
public class Menu extends MainPanel{

	private static final long serialVersionUID = 1L;
	private GameButton[] menuButton;
	private int buttonSpace, initialY;
	private LinkedList<SelectionListener> listeners = new LinkedList<SelectionListener>();
	
	//inner class for handling button clicking
	public class ButtonClicked implements ActionListener{

		//this method will be called if we clicked on a button
		public void actionPerformed(ActionEvent e) {
			boolean foundSource = false;
			int i;
			for(i = 0; (i < menuButton.length) && !foundSource; i++)
				foundSource = e.getSource() == menuButton[i];
			if(foundSource)
				notifySelectionListener(--i);
		}
		
	}
	
	//it notifies the class's own listener about an event
	public void notifySelectionListener(int menuIndex){
		SelectionEvent e = new SelectionEvent(this, menuIndex);
		for( SelectionListener i : listeners )
			i.selection(e);
	}
	
	//it adds a listener to our object
	public void addSelectionListener(SelectionListener sl){
		listeners.add(sl);
	}
	
	//menu constructor
	public Menu(String[] menuItems) {
		int buttonWidth = 400, buttonHeight = 50;
		buttonSpace = buttonHeight / 2;
		initialY = (MainWindow.getInnerHeight()-(menuItems.length-1)*(buttonHeight+buttonSpace)-buttonHeight)/2;
		menuButton = new GameButton[menuItems.length];
		for(int i=0; i<menuItems.length; i++){
			menuButton[i] = new GameButton(
					menuItems[i],
					(MainWindow.getInnerWidth()-buttonWidth)/2,
					i*(buttonHeight+buttonSpace)+initialY,
					buttonWidth,
					buttonHeight);
			menuButton[i].addActionListener(new ButtonClicked());
			add(menuButton[i]);
		}
	}

}